﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

namespace Common.Library.Helper
{
    /// <summary>
    /// JSON 序列化反序列化助手类
    /// </summary>
    public class JsonHelper
    {
        /// <summary>
        /// 序列化JSON
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string Serialize<T>(T t) where T : class
        {
            using (MemoryStream ms = new MemoryStream())
            {
                string strResult = string.Empty;
                try
                {
                    var ser = new DataContractJsonSerializer(t.GetType());
                    ser.WriteObject(ms, t);
                    byte[] json = ms.ToArray();
                    strResult = Encoding.UTF8.GetString(json, 0, json.Length);
                }
                catch (Exception ex)
                {
                    throw new Exception("序列化JSON失败!\r\n" + ex.Message, ex);
                }
                finally
                {
                    ms.Close();
                }
                return strResult;
            };
        }

        /// <summary>
        /// 序列化JSON
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="objSourceType"></param>
        /// <returns></returns>
        public static string Serialize(object obj, Type objSourceType)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                string strResult = string.Empty;
                try
                {
                    var ser = new DataContractJsonSerializer(objSourceType);
                    ser.WriteObject(ms, obj);
                    byte[] json = ms.ToArray();
                    strResult = Encoding.UTF8.GetString(json, 0, json.Length);
                }
                catch (Exception ex)
                {
                    throw new Exception("序列化JSON失败!\r\n" + ex.Message, ex);
                }
                finally
                {
                    ms.Close();
                }
                return strResult;
            };
        }

        /// <summary>
        /// 反序列化JSON
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T Deserialize<T>(string json) where T : class
        {
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
                try
                {
                    var ser = new DataContractJsonSerializer(typeof(T));
                    T result = ser.ReadObject(ms) as T;
                    ms.Close();

                    return result;
                }
                catch (Exception ex)
                {
                    throw new Exception("反序列化JSON失败!\r\n" + ex.Message, ex);
                }
                finally
                {
                    ms.Close();
                }
            }
        }

        /// <summary>
        /// 反序列化JSON
        /// </summary>
        /// <param name="json"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static object Deserialize(string json, Type type)
        {
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
                try
                {
                    var ser = new DataContractJsonSerializer(type);
                    object result = ser.ReadObject(ms);
                    ms.Close();

                    return result;
                }
                catch (Exception ex)
                {
                    throw new Exception("反序列化JSON失败!\r\n" + ex.Message, ex);
                }
                finally
                {
                    ms.Close();
                }
            }
        }

        /// <summary>
        /// JsonConvert的序列化方法 依赖Newtonsoft.Json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string JsonConvertSerialize<T>(T t)
        {
            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
            return JsonConvert.SerializeObject(t, Formatting.Indented, timeConverter);
        }

        /// <summary>
        /// JsonConvert的序列化方法(压缩JSON字符串) 依赖Newtonsoft.Json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string JsonConvertSerializeCompress<T>(T t)
        {
            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
            return JsonConvert.SerializeObject(t, Formatting.None, timeConverter);
            //return JsonConvert.SerializeObject(t, Formatting.None).Replace("\r","").Replace("\n","").Replace("\t","");
        }

        /// <summary>
        /// JsonConvert的反序列化方法 依赖Newtonsoft.Json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T JsonConvertDeserialize<T>(string json)
        {
            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
            return JsonConvert.DeserializeObject<T>(json, timeConverter);
        }

        /// <summary>
        /// JsonConvert的匿名类型反序列化方法 依赖Newtonsoft.Json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        public static T JsonConvertDeserializeAnonymousType<T>(string json, T t)
        {
            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
            return JsonConvert.DeserializeAnonymousType(json, t);
        }
    }
}
